#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QCheckBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    isCurrent = true;
    ui->setupUi(this);
    //加载样式表
    this->loadStyle();
    this->setWindowFlags(Qt::WindowCloseButtonHint);
    this->openDatab();
    this->open_winLogin();

    intro = new introduct;
    //设置列宽为自适应
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);//设置选中模式为选中行
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);  //一次只能选一行
    void (introduct::*funSignal)() = &introduct::signClicked;
    connect(intro,funSignal,this,&MainWindow::showList);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openDatab()
{
    QString path = QDir::currentPath() + "/users.db";
    QFile create(path);
    create.open(QIODevice::ReadWrite);
    create.close();

//    qDebug() << path;

    m_db = QSqlDatabase::addDatabase("QSQLITE");

    m_db.setDatabaseName(path);
    m_db.open();

    QSqlQuery query;
    query.exec("create table users(id interget not null primary key,"
                           "                    password text);");
}

void MainWindow::on_btn_timer_clicked()
{
    intro->close();
    ui->stackedWidget->setCurrentWidget(ui->timer_widget);
    if(!isTimerInit)
    {
        //未计时，倒计时
        isStart = false;
        isCountdown = true;

        TimeRecord = new QTime;
        *TimeRecord = ui->timeEdit->time();

        timer = new QTimer; //新建计时器

        ui->LCD_Timer->setDigitCount(8);
        ui->LCD_Timer->setSegmentStyle(QLCDNumber::Flat);
        ui->LCD_Timer->display(TimeRecord->toString("hh:mm:ss"));

        connect(timer,SIGNAL(timeout()),this,SLOT(updateTime()));
        isTimerInit = true;
    }

}

void MainWindow::updateTime()
{   if(!isCountdown)
        *TimeRecord = TimeRecord->addSecs(1);
    else
    {
       if(0 == TimeRecord->minute() && 0 == TimeRecord->hour() && TimeRecord->second() == 0)
       {
           //计时器停止
           this->on_btn_loop_clicked();
           QMessageBox::information(nullptr,"warning","计时结束");

       }
       else
            *TimeRecord = TimeRecord->addSecs(-1);
    };
    ui->LCD_Timer->display(TimeRecord->toString("hh:mm:ss"));
}

void MainWindow::open_winLogin()
{
    //显示登陆界面
    logWin = new Login;
    ui->stackedWidget->setCurrentIndex(0);
    logWin->show();
    isTimerInit = false;

    //登录成功，打开主界面
    auto f = [=]()
    {
        this->show();
        this->on_btn_updateList_clicked();
        logWin->hide();
    };
    connect(logWin, &Login::LoginSuccess, this, f);
}

void MainWindow::on_btn_loop_clicked()
{

    if(!isStart)
    {
        ui->btn_loop->setText("停止");
        timer->start(1000);
    }
    else
    {
        ui->btn_loop->setText("启/停");
        timer->stop();
    }
    isStart = !isStart;
}
//计时器功能使用说明：点击倒计时按钮将按照输入时间计时，更改时间后再次点击倒计时按钮使用改时间计时
//计时开始情况下无法改变模式
void MainWindow::on_btn_mode_clicked()
{
    //计时已经开启返回
    if(isStart)
    {
        QMessageBox::information(nullptr,"warning","请先停止计时！");
        return;
    }
    //倒计时更改时间功能
    if(!isCountdown)
    {
        *TimeRecord = ui->timeEdit->time();
        ui->btn_mode->setText("倒计时");
    }
    else
    {
        if(*TimeRecord != ui->timeEdit->time())
        {
            *TimeRecord = ui->timeEdit->time();
            ui->LCD_Timer->display(TimeRecord->toString("hh:mm:ss"));
            ui->btn_loop->setText("启/停");
            timer->stop();
            isStart = false;
            return;
        }
        TimeRecord = new QTime(0,0,0);
        ui->btn_mode->setText("正计时");
    };
    ui->LCD_Timer->display(TimeRecord->toString("hh:mm:ss"));
    isCountdown = !isCountdown;
    //切换模式后停止计时
    ui->btn_loop->setText("启/停");
    timer->stop();
    isStart = false;
}


void MainWindow::on_btn_list_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->list_widget);
}

void MainWindow::on_btn_site_clicked()
{
    intro->close();
    ui->stackedWidget->setCurrentWidget(ui->site_widget);

   QString temp = "用户名：" + QString::number(logWin->get_user_id());

   ui->lab_userName->setText(temp);
}

void MainWindow::on_btn_exitLog_clicked()
{
    this->close();

    this->open_winLogin();
}


void MainWindow::on_btn_updatePassword_clicked()
{
    bool bOk = false;
    QString passWord = QInputDialog::getText(nullptr,
                                         "QInputdialog",
                                         "请输入密码（至多八个字符）",
                                         QLineEdit::Password,
                                         "",
                                         &bOk
                                         );

    if (bOk && !passWord.isEmpty()) {
        passWord = passWord.left(8);
        QString md5_password = QCryptographicHash::hash(passWord.toLatin1(),QCryptographicHash::Md5).toHex();
        QSqlQuery query;
        query.exec(QString("update users set password = '%1' where id = %2").arg(md5_password).arg(logWin->get_user_id()));
    }
}
void MainWindow::on_btn_addList_clicked()
{
    intro->close();
    adLiWin = new ListAdd;
    void (ListAdd::*funSignal)() = &ListAdd::listAdd;
    connect(adLiWin,funSignal,this,&MainWindow::showList);
    adLiWin->list_Name = logWin->get_listName();
    adLiWin->show();
}

void MainWindow::on_btn_updateList_clicked()
{
    intro->close();
    isCurrent = true;
    QStringList list_finish = getList(true);
    QStringList list_unfinish = getList(false);
    ui->tableWidget->setRowCount((list_finish.size()/6 + list_unfinish.size()/6));
    //记录添加时间
    QDateTime now = QDateTime(QDate::currentDate());
    int rowCount = 0;   //记录已添加行数
    //未完成计划
    for(int i=0;i<list_unfinish.size();i += 6)
    {
        QDateTime startTime = QDateTime::fromString(list_unfinish[i+1],"hh:mm M月-dd日-yyyy");
        QDateTime endTime = QDateTime::fromString(list_unfinish[i+2],"hh:mm M月-dd日-yyyy");

        QDateTime start = QDateTime::fromString(startTime.toString("M月-dd日-yyyy"),"M月-dd日-yyyy");
        QDateTime end = QDateTime::fromString(endTime.toString("M月-dd日-yyyy"),"M月-dd日-yyyy");
        bool isTrue =  (start <= now && end >= now);
        if(isTrue)
        {
            if(QDateTime::currentDateTime() > endTime)
                ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("逾期未完成")));
            else if(QDateTime::currentDateTime() < startTime)
                ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("未开始")));
            else ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("进行中")));

            ui->tableWidget->setItem(rowCount,1,new QTableWidgetItem(list_unfinish[i]));
            ui->tableWidget->setItem(rowCount,2,new QTableWidgetItem(startTime.toString("M月dd日hh:mm")
                                     + " - " + endTime.toString("M月dd日hh:mm")));
            ui->tableWidget->setItem(rowCount,3,new QTableWidgetItem(list_unfinish[i+4]));
            rowCount++;
        }
    }

    //已完成计划
    for(int i = 0;i<list_finish.size();i += 6)
    {
        QDateTime startTime = QDateTime::fromString(list_finish[i+1],"hh:mm M月-dd日-yyyy");
        QDateTime endTime = QDateTime::fromString(list_finish[i+2],"hh:mm M月-dd日-yyyy");

        QDateTime start = QDateTime::fromString(startTime.toString("M月-dd日-yyyy"),"M月-dd日-yyyy");
        QDateTime end = QDateTime::fromString(endTime.toString("M月-dd日-yyyy"),"M月-dd日-yyyy");
        bool isTrue =  (start <= now && end >= now);
        if(isTrue)
        {
            ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("已完成")));

            ui->tableWidget->setItem(rowCount,1,new QTableWidgetItem(list_finish[i]));
            ui->tableWidget->setItem(rowCount,2,new QTableWidgetItem(startTime.toString("M月dd日hh:mm")
                                     + " - " + endTime.toString("M月dd日hh:mm")));
            ui->tableWidget->setItem(rowCount,3,new QTableWidgetItem(list_finish[i+4]));
            rowCount++;
        }

    }
    //重置列行
    ui->tableWidget->setRowCount(rowCount);
    //居中显示
    for (int i=0;i<rowCount;i++)
       {
           for (int j=0;j<4;j++)
           {
               ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
           }
       }
}

QStringList MainWindow::getList(bool isFinish)
{
    QStringList list;
    QString order = nullptr;
    if(isFinish)
        order = QString("select * from %1 where isFinish != 'no'").arg(logWin->get_listName());
    else
        order = QString("select * from %1 where isFinish = 'no'").arg(logWin->get_listName());
    QSqlQuery query;
    query.exec(order);
    while(query.next())
    {
        for(int i=0;i<6;i++)
            list.push_back(query.value(i).toString());
    }
    return list;
}

void MainWindow::setTimeRecord()
{
    int lastTime = linkWidget->getLastTime();
    if(lastTime == 0) return;
    if(!isCountdown || isStart)
    {
        QMessageBox::information(nullptr,"warning","需要更改为倒计时模式并停止计时");
        return;
    }
    int hours = lastTime / 60;
    int mins = lastTime % 60;
    *TimeRecord = QTime(hours,mins);
    ui->LCD_Timer->display(TimeRecord->toString("hh:mm:ss"));
    this->on_btn_loop_clicked();
}


//双击一个计划时显示详细介绍（另起窗口）
void MainWindow::on_tableWidget_cellDoubleClicked(int row, int column)
{
    intro->show();
    QString addTime = ui->tableWidget->item(row,3)->text();
    QString planName = ui->tableWidget->item(row,1)->text();
    QString giveOrder;
    giveOrder = QString("update %1 set isFinish = 'yes' where add_time = '%2'").arg(logWin->get_listName()).arg(addTime);
    intro->setOrderText(giveOrder);
    //获取介绍
    QString order,introduction;
    order= QString("select introduction from %1 where add_time = '%2'").arg(logWin->get_listName()).arg(addTime);
//    qDebug() << order;
    QSqlQuery query;
    query.exec(order);
    while(query.next())
       introduction = query.value(0).toString();
    intro->setTitle(planName);
    intro->setText(introduction);
    intro->setGeometry(this->pos().x() + this->geometry().width() + 12,this->pos().y()+(this->geometry().height()/2-150),550,400);

}

void MainWindow::on_btn_link_clicked()
{
    linkWidget = new LinkList;
    linkWidget->setWindowModality(Qt::ApplicationModal);
    linkWidget->show();
    linkWidget->setLists(getList(false));
    linkWidget->createTable();
    void (LinkList::*funSignal2)() = &LinkList::doubleCLicked;
    connect(linkWidget,funSignal2,this,&MainWindow::setTimeRecord);
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    intro->close();
}
//删除选中计划
void MainWindow::on_btn_deleteList_clicked()
{
    QList<QTableWidgetItem*>items=ui->tableWidget->selectedItems();
    if(items.isEmpty())
    {
        QMessageBox::information(nullptr,"warning","未选中任何内容");
        return;
    }
    //获取已选中的行号
    int rowCount = items[0]->row();
    QString addTime = ui->tableWidget->item(rowCount,3)->text();
    QSqlQuery query;
    QString order = QString("delete from %1 where add_time = '%2'").arg(logWin->get_listName()).arg(addTime);
    query.exec(order);
    //刷新菜单
    this->showList();
}
//显示所有计划
void MainWindow::on_btn_allList_clicked()
{
    intro->close();
    isCurrent = false;
    QStringList list_finish = getList(true);
    QStringList list_unfinish = getList(false);

    ui->tableWidget->setRowCount((list_finish.size()/6 + list_unfinish.size()/6));
    int rowCount = 0;   //记录已添加行数
    //未完成计划
    for(int i=0;i<list_unfinish.size();i += 6,rowCount++)
    {
        QDateTime start_time = QDateTime::fromString(list_unfinish[i+1],"hh:mm M月-dd日-yyyy");
        QDateTime end_time = QDateTime::fromString(list_unfinish[i+2],"hh:mm M月-dd日-yyyy");
        //设置计划状态一栏
        if(QDateTime::currentDateTime() > end_time)
            ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("逾期未完成")));
        else if(QDateTime::currentDateTime() < start_time)
            ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("未开始")));
        else ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("进行中")));

        ui->tableWidget->setItem(rowCount,1,new QTableWidgetItem(list_unfinish[i]));
        ui->tableWidget->setItem(rowCount,2,new QTableWidgetItem(QDateTime::fromString(list_unfinish[i+1],"hh:mm M月-dd日-yyyy").toString("M月dd日hh:mm")
                                 + " - " + QDateTime::fromString(list_unfinish[i+2],"hh:mm M月-dd日-yyyy").toString("M月dd日hh:mm")));
        ui->tableWidget->setItem(rowCount,3,new QTableWidgetItem(list_unfinish[i+4]));
    }
    //已完成计划
    for(int i = 0;i<list_finish.size();i += 6,rowCount++)
    {

        ui->tableWidget->setItem(rowCount,0,new QTableWidgetItem(QString("已完成")));

        ui->tableWidget->setItem(rowCount,1,new QTableWidgetItem(list_finish[i]));
        ui->tableWidget->setItem(rowCount,2,new QTableWidgetItem(QDateTime::fromString(list_finish[i+1],"hh:mm M月-dd日-yyyy").toString("M月dd日hh:mm")
                                 + " - " + QDateTime::fromString(list_finish[i+2],"hh:mm M月-dd日-yyyy").toString("M月dd日hh:mm")));
        ui->tableWidget->setItem(rowCount,3,new QTableWidgetItem(list_finish[i+4]));
    }

    //居中显示
    for (int i=0;i<rowCount;i++)
       {
           for (int j=0;j<4;j++)
           {
               ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
           }
    }
}

void MainWindow::showList()
{
    if(isCurrent)
    {
        this->on_btn_updateList_clicked();
    }
    else
    {
        this->on_btn_allList_clicked();
    }
}

void MainWindow::loadStyle()
{
    QString styleSheetFile = ":/new/prefix2/StyleSheet/mainwindowStyle.qss";
    QFile file(styleSheetFile);
    file.open(QFile::ReadOnly);
    if (file.isOpen())
    {
        QString styleSheet = this->styleSheet();
        styleSheet += QLatin1String(file.readAll());//读取样式表文件
        this->setStyleSheet(styleSheet);
        file.close();
    }
//    else
//    {
//        QMessageBox::information(this,"tip","cannot find qss file");
//    }

}
